import type { SpColumnsType } from '@/components/SpTable/type'
import { message, Tag } from 'ant-design-vue'
import { addDialog } from '@/components/SpDialog/index'
import ModalForm from '../form/modal.vue'
import type { FormExpose } from 'ant-design-vue/es/form/Form'
import type { MenuType, MenuTypeWriteParamsType } from './model'
import { addMenuAPI, deleteMenuAPI, getMenuListAPI, updateMenuAPI } from './api'
import Icon from '@/components/icon/Icon.vue'
import { formattedChildrenUndefined } from '@/utils/tree'
import { cloneDeep } from 'lodash'
import { transformI18n } from '@/plugins/i18n'
import type { SysRoleListType } from '@/views/admin/system/role/utils/model'
import { getRoleListAPI } from '@/views/admin/system/role/utils/api'

export function useMenu() {
  // 表格列
  const columns: SpColumnsType[] = [
    {
      title: '菜单名称',
      dataIndex: 'title',
      width: 300,
      cellRenderer: (record: MenuType) => (
        <>
          {record.icon != '' ? <Icon style={{ marginRight: '5px' }} type={record.icon} /> : ''}
          {transformI18n(record.title as any)}
        </>
      )
    },
    {
      title: '菜单类型',
      dataIndex: 'status',
      cellRenderer: (record: MenuType) => {
        if (record.isMenu === 1) {
          return <Tag color="green">菜单</Tag>
        } else {
          return <Tag color="blue">权限</Tag>
        }
      },
      width: 100,
      align: 'center'
    },
    {
      title: '菜单路径',
      dataIndex: 'path',
      align: 'center',
      width: 300
    },
    {
      title: '权限标识',
      dataIndex: 'perms',
      align: 'center',
      width: 300
    },
    {
      title: '排序值',
      dataIndex: 'rank',
      align: 'center',
      width: 100
    },
    {
      title: '菜单隐藏',
      dataIndex: 'status',
      cellRenderer: (record: MenuType) => {
        if (record.showLink === 1) {
          return <Tag color="green">否</Tag>
        } else {
          return <Tag color="red">是</Tag>
        }
      },
      align: 'center',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 250,
      align: 'center'
    }
  ]
  // 加载状态
  const loading = ref(false)
  // 菜单树
  const dataList = ref<MenuType[]>([])
  // 用户列表
  const roleList = ref<SysRoleListType[]>([])
  // 弹窗框Ref
  const modalRef = ref()

  // 获取菜单树
  function getDataList() {
    loading.value = true
    getMenuListAPI().then((res) => {
      formattedChildrenUndefined(res.data)
      dataList.value = res.data
      loading.value = false
    })
  }

  // 过滤语言
  function filterTreeLanguage(data: MenuType[]) {
    return data.map((v) => {
      v.title = transformI18n(v.title as any)
      if (v.children) {
        v.children = filterTreeLanguage(v.children)
      }
      return v
    })
  }

  // 获取用户列表
  function getUserList() {
    getRoleListAPI({ pageSize: 999999 }).then((res) => {
      roleList.value = res.data.rows
    })
  }

  // 打开弹窗
  function openModal(title: string, data?: MenuType) {
    const tree = cloneDeep(dataList.value)
    addDialog({
      title: `${title}菜单`,
      width: '50%',
      contentRenderer: () =>
        h(ModalForm, {
          ref: modalRef,
          data: data ?? {},
          title: title,
          treeData: filterTreeLanguage(tree) ?? [],
          roleList: roleList.value ?? []
        }),
      beforeSure: function (done) {
        // 关闭弹窗
        function chores(title: string, done: Function) {
          message.success(`${title}成功`)
          done()
          getDataList()
        }
        const form = modalRef.value.getRef() as FormExpose
        form.validate().then((res) => {
          const formData = res as MenuTypeWriteParamsType
          if (title == '编辑') {
            updateMenuAPI(data?.id as number, formData).then(() => {
              chores(title, done)
            })
          } else {
            addMenuAPI(formData).then(() => {
              chores(title, done)
            })
          }
        })
      }
    })
  }

  // 删除
  const deleteData = (data: MenuType) => {
    deleteMenuAPI(data.id as number).then(() => {
      message.success(`您删除了菜单名称为${transformI18n(data.title as any)}的这条数据`)
      getDataList()
    })
  }

  onMounted(() => {
    getDataList()
    getUserList()
  })

  return {
    columns,
    loading,
    dataList,
    openModal,
    deleteData
  }
}
